package cn.com.Controller;

import cn.com.Service.RedisSaveManageService;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;

import org.apache.shiro.subject.Subject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



/**
 * Created by luokun on 2018/3/15.
 */
@Controller
@Slf4j
public class ShiroAction {
    @Autowired
    private RedisSaveManageService redisSaveManageService;

    @RequestMapping("/logins")
    public String logins() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, HttpSession httpSession, HttpServletResponse response) throws Exception {
        String name = request.getParameter("name");
        String password = request.getParameter("password");


        Integer account=  redisSaveManageService.get(name);
        if(account>5){
            return "error";
        }
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        Subject currentUser = SecurityUtils.getSubject();
        try {
            if (!currentUser.isAuthenticated()) {
                currentUser.login(token);

                if(redisSaveManageService.get(name)!=0) {
                    redisSaveManageService.del(name);
                }

              /*  Cookie cookie = new Cookie("session"+name, httpSession.getId().toString());       //(key,value)
                cookie.setPath("/");// 这个要设置
                cookie.setMaxAge (60*60);// 不设置的话，则cookies不写入硬盘,而是写在内存,只在当前页面有用,以秒为单位
                response.addCookie(cookie);*/
                return "welcome";
            }
        }catch (UnknownAccountException e){
            log.info("用户"+name+"不存在");
        }catch (AuthenticationException e) {
                redisSaveManageService.increment(name, 100);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "login";
    }
    @RequestMapping("/shiro/errorlogin")
    public String Welcome(HttpServletRequest request) {
        return "success";
    }

}
